﻿using System;
using System.ComponentModel;

namespace InputBoxes.Controls
{
    [ToolboxItem(false)]
    public partial class SingleLineTextBasedInputBoxBase : InputBoxBase
    {
        private string _previousText;

        public SingleLineTextBasedInputBoxBase()
        {
            InitializeComponent();
            SetEditor(ValueTextBox);
        }

        public override string Text
        {
            get { return ValueTextBox.Text; }
            set
            {
                _previousText = ValueTextBox.Text;
                ValueTextBox.Text = value;
            }
        }

        public bool ReadOnly
        {
            get { return ValueTextBox.ReadOnly; }
            set { ValueTextBox.ReadOnly = value; }
        }

        public event ValueTextChangedEvent ValueTextChanged;

        private void ValueTextBox_TextChanged(object sender, EventArgs e)
        {
            PerformValidate();
            OnValueTextChanged(_previousText, () => GetIsValid(_previousText), Text, () => GetIsValid(Text));
        }

        private void OnValueTextChanged(string previousText, Func<bool> getPreviousValid, string currentText, Func<bool> getCurrentValid)
        {
            if (ValueTextChanged != null)
            {
                ValueTextChanged(this, new ValueTextChangedEventArgs(previousText, getPreviousValid(), currentText, getCurrentValid()));
            }
        }
    }
}
